package hotel.base.oversea.utils;

import redis.clients.jedis.Jedis;

import java.util.Random;

public class RedisTest {

    private static String[] keys = new String[1000];

    private static String randomString(int length) {
        Random random = new Random();
        char[] chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
        StringBuilder key = new StringBuilder(length);
        int i = length;
        while (i > 0) {
            key.append(chars[random.nextInt(chars.length)]);
            i--;
        }
        return key.toString();
    }

    private static void write(Jedis jedis, int length) {
        long start = System.currentTimeMillis();
        String key = null;
        String value = null;
        for (int i = 0; i < 1000; i++) {
            key = randomString(length);
            keys[i] = key;
            value = randomString(1000);
            jedis.set(key, value);
        }
        System.out.println(String.format("put key length %d with value length 1000 in 1000 tims costs: %d ms", length, System.currentTimeMillis() - start));
    }

    private static void read(Jedis jedis, int length) {
        long start = System.currentTimeMillis();
        for (int i = 0; i < keys.length; i++) {
            jedis.get(keys[i]);
        }
        System.out.println(String.format("get key length %d with value length 1000 in 1000 tims costs: %d ms", length, System.currentTimeMillis() - start));
    }

    public static void main(String[] args) throws InterruptedException {
        Jedis jedis = new Jedis("192.168.1.10", 6379,5000,10000);
        jedis.auth("123456");
        int[] lengths = {10, 100, 500, 1000, 2500, 5000, 7500, 10000, 20000};
        for (int i = 0; i < lengths.length; i++) {
            write(jedis, lengths[i]);
            read(jedis, lengths[i]);
            keys = new String[1000];
            jedis.flushAll();
        }
        System.out.println();
    }
}
